﻿using System;
using System.Collections.Generic;

namespace Flagwind.Externals.Redis.Commands
{
	public class DictionarySetCommand : RedisCommandBase
	{
		#region 构造方法

		public DictionarySetCommand() : base("Set")
		{
		}

		public DictionarySetCommand(IRedisService redis) : base(redis, "Set")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length < 3)
				throw new Flagwind.Services.CommandException("Missing arguments.");

			var dictionary = this.Redis.GetDictionary(context.Expression.Arguments[0]);

			if(dictionary == null)
			{
				context.Error.WriteLine($"The '{context.Expression.Arguments[0]}' dictionary is not existed.");
				return false;
			}

			if(context.Expression.Arguments.Length == 3)
			{
				dictionary[context.Expression.Arguments[1]] = context.Expression.Arguments[2];
				return true;
			}

			var items = new KeyValuePair<string, string>[(context.Expression.Arguments.Length - 1) / 2];

			for(int i = 0; i < items.Length; i++)
			{
				items[i] = new KeyValuePair<string, string>(context.Expression.Arguments[i * 2 + 1], context.Expression.Arguments[i * 2 + 2]);
			}

			dictionary.SetRange(items);

			return true;
		}

		#endregion
	}
}